package ltd.sshine.networkclient.runner;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import ltd.sshine.networkclient.config.ServerConfig;
import ltd.sshine.networkclient.utils.ClientUtils;
import ltd.sshine.networkcommon.config.ConnectConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.CommandLineRunner;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ClientRunner implements CommandLineRunner, DisposableBean {
    private final Bootstrap bootstrap;
    private final ObjectMapper objectMapper;
    private final ServerConfig serverConfig;
    private ChannelFuture connect;
    public ClientRunner(ObjectMapper objectMapper, ServerConfig serverConfig, ClientUtils clientUtils) {
        this.bootstrap = clientUtils.createClientBootstrap();
        this.objectMapper = objectMapper;
        this.serverConfig=serverConfig;
    }

    @Override
    public void destroy() {
        if (connect!=null){
            connect.channel().close();
            log.info("正在关闭network-helper");
        }
    }

    @Override
    public void run(String... args) {
        connect = bootstrap.connect(new InetSocketAddress(serverConfig.getHost(), serverConfig.getPort()));
        connect.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                ConnectConfig connectConfig = new ConnectConfig();
                BeanUtils.copyProperties(serverConfig, connectConfig);
                future.channel().writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(
                        objectMapper.writeValueAsString(connectConfig).getBytes(StandardCharsets.UTF_8)
                ));
            } else {
                log.error("连接失败");
                connect.channel().close();
            }
        });
    }
}
